import { Room } from "./room";
import { SignalMessage } from "../type";
import * as ws from 'ws';

const rooms = new Map<string, Room>();
rooms.set("default", new Room("default"));
function createRoom(websocket:ws.WebSocket,clientId:string):string{
    const room = new Room();
    rooms.set(room.getRoomId(), room);
    room.joinRoom(clientId, websocket);
    return room.getRoomId();
}

function deleteRoom(roomId: string){ 
    rooms.delete(roomId);
}

function joinRoom(roomId: string, clientId: string, websocket: ws.WebSocket){
    if(!rooms.has(roomId)){
        console.log("Room not found");
        return
    }
    console.log("Joining room " + roomId)
    rooms.get(roomId)!.joinRoom(clientId, websocket);
}

function onOffer(roomId: string, msg: SignalMessage){
    rooms.get(roomId)?.handleOffer(msg);
}

function onAnswer(roomId: string, msg: SignalMessage){
    rooms.get(roomId)?.handleAnswer(msg);
}

function onCandidate(roomId: string, msg: SignalMessage){
    rooms.get(roomId)?.handleCandidate(msg);
}

export {createRoom,deleteRoom,onOffer,onAnswer,onCandidate,rooms,joinRoom};